package com.example.asa;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;

@WebServlet("/updateDisaster")
public class UpdateDisasterServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        int id = Integer.parseInt(request.getParameter("id"));
        Disaster disaster = getDisasterById(id);
        if (disaster != null) {
            request.setAttribute("disaster", disaster);
            request.getRequestDispatcher("editDisaster.jsp").forward(request, response);
        } else {
            response.sendRedirect("disasterManage.jsp");
        }
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        int id = Integer.parseInt(request.getParameter("id"));
        String name = request.getParameter("name");
        String timestamp = request.getParameter("timestamp");
        String location = request.getParameter("location");
        String affectedArea = request.getParameter("affected_area");
        String description = request.getParameter("description");
        String status = request.getParameter("status");
        String severity = request.getParameter("severity");
        String contact = request.getParameter("contact");

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        java.sql.Timestamp sqlTimestamp;
        try {
            sqlTimestamp = new java.sql.Timestamp(sdf.parse(timestamp).getTime());
        } catch (java.text.ParseException e) {
            request.setAttribute("message", "时间格式不正确，请使用格式：yyyy-MM-dd HH:mm:ss");
            request.getRequestDispatcher("/editDisaster.jsp").forward(request, response);
            return;
        }
        updateDisaster(id, name, timestamp, location, affectedArea, description, status, severity, contact);
        response.sendRedirect("disasterManage.jsp");
    }

    private Disaster getDisasterById(int id) {
        Connection conn = null;
        PreparedStatement stmt = null;
        ResultSet rs = null;
        Disaster disaster = null;

        try {
            conn = DatabaseUtil.getConnection();
            stmt = conn.prepareStatement("SELECT * FROM disasters WHERE id = ?");
            stmt.setInt(1, id);
            rs = stmt.executeQuery();

            if (rs.next()) {
                disaster = new Disaster();
                disaster.setId(rs.getInt("id"));
                disaster.setName(rs.getString("name"));
                disaster.setTimestamp(rs.getTimestamp("timestamp"));
                disaster.setLocation(rs.getString("location"));
                disaster.setAffectedArea(rs.getString("affected_area"));
                disaster.setDescription(rs.getString("description"));
                disaster.setStatus(rs.getString("status"));
                disaster.setSeverity(rs.getString("severity"));
                disaster.setContact(rs.getString("contact"));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try { if (rs != null) rs.close(); } catch (SQLException ignored) {}
            try { if (stmt != null) stmt.close(); } catch (SQLException ignored) {}
            try { if (conn != null) conn.close(); } catch (SQLException ignored) {}
        }

        return disaster;
    }

    private void updateDisaster(int id, String name, String timestamp, String location, String affectedArea, String description, String status, String severity, String contact) {
        Connection conn = null;
        PreparedStatement stmt = null;

        try {
            conn = DatabaseUtil.getConnection();
            stmt = conn.prepareStatement("UPDATE disasters SET name = ?, timestamp = ?, location = ?, affected_area = ?, description = ?, status = ?, severity = ?, contact = ? WHERE id = ?");
            stmt.setString(1, name);
            stmt.setTimestamp(2, Timestamp.valueOf(timestamp));
            stmt.setString(3, location);
            stmt.setString(4, affectedArea);
            stmt.setString(5, description);
            stmt.setString(6, status);
            stmt.setString(7, severity);
            stmt.setString(8, contact);
            stmt.setInt(9, id);

            stmt.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try { if (stmt != null) stmt.close(); } catch (SQLException ignored) {}
            try { if (conn != null) conn.close(); } catch (SQLException ignored) {}
        }
    }
}
